//
//  ViewController.m
//  TZImagePickerController
//
//  Created by 谭真 on 15/12/24.
//  Copyright © 2015年 谭真. All rights reserved.
//

#import "ViewController.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "TZTestCell.h"
#import "CoreDataHandle.h"
#import "Photos.h"
#import "BigImageViewController.h"

@interface ViewController ()<TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate> {
    UICollectionView *_collectionView;
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;

    CGFloat _itemWH;
    CGFloat _margin;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _selectedPhotos = [NSMutableArray array];
     [self arrayGetData];
    _selectedAssets = [NSMutableArray array];
    [self configCollectionView];
    UIBarButtonItem  *rightIrem = [[UIBarButtonItem alloc]initWithTitle:@"添加图片" style: UIBarButtonItemStylePlain target:self action:@selector(itemClickedAction:)];
    self.navigationItem.rightBarButtonItem = rightIrem;
    UIBarButtonItem  *leftItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style: UIBarButtonItemStylePlain target:self action:@selector(leftItemClickedAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    
}
-(void)itemClickedAction:(UIBarButtonItem *)sender{
     [self pickPhotoButtonClick:nil];

}
-(void)leftItemClickedAction:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
    

}


//从数据库初始化数组
-(void)arrayGetData{
    [[CoreDataHandle shareCoreDataHandle] getCoreData];
    
    //创建请求对象,并且指明所有数据的类型
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Photos"];
    NSArray *objectArray =    [[CoreDataHandle shareCoreDataHandle].context executeFetchRequest:request error:nil];
    NSMutableArray *arr = [NSMutableArray array];
    if (objectArray) {
        for (Photos *object in objectArray) {
                 NSString * conStr = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:object.imageStr];
            UIImage *image = [UIImage imageWithContentsOfFile:conStr];
            [arr addObject:image];
////            NSLog(@"%@",object.imageStr);
//            
                }
        [_selectedPhotos addObjectsFromArray:arr];
       
    }
 }





- (void)configCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _margin = 4;
    _itemWH = (self.view.width - 2 * _margin - 4) / 3 - _margin;
    layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    layout.minimumInteritemSpacing = _margin;
    layout.minimumLineSpacing = _margin;
    _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    CGFloat rgb = 244 / 255.0;
    _collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.contentInset = UIEdgeInsetsMake(4, 0, 0, 2);
    _collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn"];
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {[self pickPhotoButtonClick:nil];}else{
     
        UIAlertController * alertControlller = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择需要进行的操作" preferredStyle:    UIAlertControllerStyleAlert];
        UIAlertAction *  inAction = [UIAlertAction actionWithTitle:@"浏览大图" style:  UIAlertActionStyleDefault  handler:^(UIAlertAction * _Nonnull action) {
            BigImageViewController *bigVC = [[BigImageViewController alloc]init];
            bigVC.indexpath = indexPath.row;
            [self.navigationController pushViewController:bigVC animated:YES];
            
      }];
        UIAlertAction *  cancelAction = [UIAlertAction actionWithTitle:@"退出" style:  UIAlertActionStyleDefault  handler:nil];
        UIAlertAction * deleateAction = [UIAlertAction actionWithTitle:@"删除图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Photos"];
            NSArray *objectArray =    [[CoreDataHandle shareCoreDataHandle].context executeFetchRequest:request error:nil];
            Photos *photos = objectArray[indexPath.row];
            [[CoreDataHandle shareCoreDataHandle].context deleteObject:photos];
      
            //查看context是否有改变,有的话保存®
            if ([[CoreDataHandle shareCoreDataHandle].context  hasChanges]) {
                [[CoreDataHandle shareCoreDataHandle].context  save:nil];
            }
            [_selectedPhotos  removeObject:_selectedPhotos[indexPath.row]];
            [_collectionView reloadData];
        }];
            [alertControlller addAction:inAction];
            [alertControlller addAction:deleateAction];
            [alertControlller addAction:cancelAction];
            [self.navigationController presentViewController:alertControlller animated:YES completion:nil];
    

        
            
    }

 
    
}


#pragma mark Click Event

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
        NSDate *  timeDate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"HHmmss"];
      NSString *  locationString=[dateformatter stringFromDate:timeDate];
        for (int i  = 0; i<photos.count; i++) {
            NSString *nameStr = [NSString stringWithFormat:@"(%d).jpg",i];
            NSString *str = [locationString stringByAppendingString:nameStr];
            Photos *p =  [NSEntityDescription insertNewObjectForEntityForName:@"Photos" inManagedObjectContext:[CoreDataHandle shareCoreDataHandle].context];
            p.imageStr = str;
       
    
            if ([[CoreDataHandle shareCoreDataHandle].context hasChanges]) {
                [[CoreDataHandle shareCoreDataHandle].context save:nil];
            }
            [self saveImage:photos[i] withName:str];
            
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    NSLog(@"%@+++++++",fullPath);
    
    [imageData writeToFile:fullPath atomically:NO];
}



#pragma mark TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    NSLog(@"cancel");
}

/// User finish picking photo，if assets are not empty, user picking original photo.
/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    [_collectionView reloadData];
    _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

/// User finish picking video,
/// 用户选择好了视频
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    [_selectedPhotos addObjectsFromArray:@[coverImage]];
    [_collectionView reloadData];
    _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}


@end
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com